package cn.com.nes.site.service.system.user.impl;

import cn.com.nes.common.exception.BusinessException;
import cn.com.nes.common.exception.IllegalBusinessException;
import cn.com.nes.common.exception.MissBusinessParameterException;
import cn.com.nes.common.util.*;
import cn.com.nes.mybatis.agent.project.entity.ProjectServiceUserAuth;
import cn.com.nes.mybatis.agent.project.entity.TProject;
import cn.com.nes.mybatis.agent.system.entity.Company;
import cn.com.nes.mybatis.agent.system.entity.RepairUser;
import cn.com.nes.mybatis.agent.system.entity.TRole;
import cn.com.nes.mybatis.agent.system.entity.TUser;
import cn.com.nes.mybatis.agent.system.mapper.TUserMapper;
import cn.com.nes.mybatis.callcenter.entity.WorkOrderInfo;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.bo.user.GetInstallPersonListBO;
import cn.com.nes.site.entity.bo.user.TUserBo;
import cn.com.nes.site.entity.em.DeleteEnum;
import cn.com.nes.site.entity.em.UserTypeEnum;
import cn.com.nes.site.entity.em.project.ProjectServiceUserTypeEnum;
import cn.com.nes.site.entity.vo.NullVO;
import cn.com.nes.site.entity.vo.system.GetAuthTokenByErUserIdVO;
import cn.com.nes.site.entity.vo.system.GetAuthTokenVO;
import cn.com.nes.site.entity.vo.system.GetOtherInstallUserVO;
import cn.com.nes.site.entity.vo.system.UpdateUserInfoFromEasyRepairVO;
import cn.com.nes.site.entity.vo.user.PushUserInfoVO;
import cn.com.nes.site.service.crm.flow.CrmFlowTableRelationshipService;
import cn.com.nes.site.service.project.ProjectServiceUserAuthService;
import cn.com.nes.site.service.project.TProjectService;
import cn.com.nes.site.service.project.dto.MyTeamInfoDTO;
import cn.com.nes.site.service.system.callCenter.CallCenterService;
import cn.com.nes.site.service.system.company.BusinessCompanyService;
import cn.com.nes.site.service.system.region.XzqhService;
import cn.com.nes.site.service.system.role.SystemRoleService;
import cn.com.nes.site.service.system.user.PushUserInfoServiceFactory;
import cn.com.nes.site.service.system.user.SystemUserService;
import cn.com.nes.site.service.system.user.bo.QueryInstallUsersBO;
import cn.com.nes.site.service.system.user.bo.QueryRepairUsersBO;
import cn.com.nes.site.service.system.user.bo.SaveERUserBO;
import cn.com.nes.site.service.workOrder.WorkOrderService;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SystemUserServiceImpl extends ServiceImpl<TUserMapper, TUser> implements SystemUserService {

    @Resource
    private CallCenterService callCenterService;

    @Resource
    private BusinessCompanyService businessCompanyService;

    @Resource
    private PushUserInfoServiceFactory pushUserInfoServiceFactory;

    @Resource
    private SystemRoleService systemRoleService;

    @Lazy
    @Resource
    private ProjectServiceUserAuthService projectServiceUserAuthService;

    @Lazy
    @Resource
    private TProjectService tProjectService;

    @Lazy
    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private CrmFlowTableRelationshipService crmFlowTableRelationshipService;

    @Resource
    private XzqhService xzqhService;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public PageData batchInitUserPassword() throws Exception {
        List<TUser> allUnDeletedUsers = this.baseMapper.getAllUnDeletedUsers();

        for (TUser user : allUnDeletedUsers) {
            user.setPassword(PasswordUtils.encrypt(user.getUsername()));
            this.baseMapper.updateById(user);
        }
        return PageData.ok();
    }

    /**
     * @param userId
     * @return 0-非代理 1-是代理
     */
    @Override
    public Byte getIsAgent(String userId) throws Exception {
        Byte isAgent = 0; // 不是代理商

        String companyType = this.baseMapper.getCompanyType(userId);
        if (StrUtil.isNotBlank(companyType) && "02".equals(companyType)) {
            isAgent = 1; // 是代理商
        }
        return isAgent;
    }

    @Override
    public TUser getUserInfoByUserId(String userId) {
        return this.baseMapper.getUserDetailByUserId(userId);
    }
     @Override
     public  TUser getUserInfoByCallCenterUserId(String callCenterUserId){
        return this.baseMapper.getUserInfoByCallCenterUserId(callCenterUserId);
    }
    @Override
   /* @Async*/
    public void pushUserInfo(PushUserInfoVO vo) {
        String uuid = vo.getUuid();
        log.info("开始推送易修、客服中心用户账号,uuid:{}", uuid);
        try {
            // 1、根据uuid查询用户信息
            TUser userInfo = this.baseMapper.getAllUserByUuId(uuid);
            userInfo.setPassword(vo.getPassword());

            // 2、查询易修账号占用情况
            if (ObjectUtil.isNotNull(userInfo.getEasyRepairUserId())) {
                Integer count = this.baseMapper.getEasyRepairUserIdCount(uuid, userInfo.getEasyRepairUserId());
                vo.setNobodyUsedEasyRepairUserId(0 == count);
            }

            // 3、调接口推送用户信息
            pushUserInfoServiceFactory.getPushUserInfoService(vo.getPushType()).handle(userInfo, vo);

        } catch (Exception e) {
            log.error("热链云公司：{}, 热链云用户：{} 创建失败：{}", vo.getCompanyId(), uuid, e.getMessage());
        }
        log.info("推送易修、长效管护用户完成");
    }

    @Override
    public String getCompanyId(String callCenterCompanyId) throws Exception {
        return businessCompanyService.getCompany(callCenterCompanyId).getCompanyid();
    }

    @Override
    public List<String> getUserIdList(String companyId) {
        return this.baseMapper.getUserIdList(companyId);
    }

    @Override
    public PageData getAuthToken(GetAuthTokenVO vo) throws Exception {
        TUserBo user = getSystemUser(vo.getCompanyId(), vo.getUserId());
        JwtUtil util = new JwtUtil();
        String key = util.createJWT(user.getUsername(), JsonUtil.getStriFromObj(user), Globals.TOKEN_TIME);
        return PageData.ok("key", key);
    }

    @Override
    public PageData getAuthTokenByErUserId(GetAuthTokenByErUserIdVO vo) throws Exception {
        TUserBo user = getSystemUserByErUserId(vo.getCompanyId(), vo.getErUserId());
        JwtUtil util = new JwtUtil();
        String key = util.createJWT(user.getUsername(), JsonUtil.getStriFromObj(user), Globals.TOKEN_TIME);
        return PageData.ok("key", key);
    }

    @Override
    public boolean hasUsers(String companyIdOrDepartmentId) throws Exception {
        List<TUser> usersInDepartment = this.getUsers(companyIdOrDepartmentId);
        if (CollUtil.isNotEmpty(usersInDepartment)) {
            return true;
        }
        return false;
    }

    @Override
    public void removeUserFormDepartment(String departmentId, Long operateUserId, Date operateDate) {
        this.baseMapper.removeUserDepartment(departmentId, operateUserId, operateDate);
    }

    @Override
    public List<TUser> getUsers(String companyIdOrDepartmentId) throws Exception {
        return this.baseMapper.getUsers(companyIdOrDepartmentId);
    }

    @Override
    public List<RepairUser> getRepairUser(String companyIdOrDepartmentId){
        return this.baseMapper.getRepairUser(companyIdOrDepartmentId);
    }

    @Override
    public List<TUser> getUsers(Long erUserId) throws Exception {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("easy_repair_user_id", erUserId);
        queryWrapper.eq("sfsc", 0);
        return this.baseMapper.selectList(queryWrapper);
    }

    public List<TUser> getUsers(String companyId, Long erUserId) throws Exception {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("companyId", companyId);
        queryWrapper.eq("easy_repair_user_id", erUserId);
        queryWrapper.eq("sfsc", 0);
        return this.baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<TUser> getUsers(List<Long> userIds) throws Exception {
        if (CollUtil.isEmpty(userIds)) {
            return Collections.emptyList();
        }
        List<TUser> users = (List<TUser>) this.listByIds(userIds);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }

        return users.stream()
                .filter(user -> user.getSfsc().equals(DeleteEnum._0.getKey()))
                .collect(Collectors.toList());
        // QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        // queryWrapper.in("id", userIds);
        // queryWrapper.eq("sfsc", 0);
        // return this.baseMapper.selectList(queryWrapper);
    }

    public List<RepairUser> getRepairUserSelect(String companyOrDepartmentId) throws Exception {
        List<RepairUser> users = getRepairUser(companyOrDepartmentId, UserTypeEnum._01);
        users.addAll(getRepairUser(companyOrDepartmentId, UserTypeEnum._08));
        return users;
    }
    public List<TUser> getPcRepairUsers (String companyOrDepartmentId)throws Exception {
        List<TUser> users = getUsers(companyOrDepartmentId, UserTypeEnum._01);
        users.addAll(getUsers(companyOrDepartmentId, UserTypeEnum._08));
        return users;
    }

    public List<TUser> getInstallUserSelect(String companyOrDepartmentId) throws Exception {
        List<TUser> users = getUsers(companyOrDepartmentId, UserTypeEnum._02);
        users.addAll(getUsers(companyOrDepartmentId, UserTypeEnum._08));
        users.addAll(getUsers(companyOrDepartmentId, UserTypeEnum._01));
        return users;
    }
    @Override
    public List<TUser> getInstallUsers(QueryInstallUsersBO bo) throws Exception {
        // 按项目ID，查询安装人员
        if (StrUtil.isNotEmpty(bo.getProjectIdOrUuid())) {
            TProject project = tProjectService.getProject(bo.getProjectIdOrUuid());
            List<ProjectServiceUserAuth> projectServiceUserAuths = projectServiceUserAuthService.getProjectServiceUsers(project.getUuid());
            // 部门ID不为空，查询该部门的项目服务人员权限。
            if (StrUtil.isNotEmpty(bo.getDepartmentId())) {
                projectServiceUserAuths = projectServiceUserAuths.stream().filter(auth -> bo.getDepartmentId().equals(auth.getDepartmentId())).collect(Collectors.toList());
            }
            if (CollUtil.isNotEmpty(projectServiceUserAuths)) {
                List<Long> serviceUserIds = projectServiceUserAuths.stream().filter(auth -> ProjectServiceUserTypeEnum.CONSTRUCTION_MANAGER.getKey().equals(auth.getServiceUserType()))
                        .map(ProjectServiceUserAuth::getServiceUserId)
                        .collect(Collectors.toList());

                List<TUser> users = this.getUsers(serviceUserIds);
                return users.stream()
                        .filter(user -> UserTypeEnum._02.getKey()
                                .equals(user.getUserType()) || UserTypeEnum._01.getKey()
                                .equals(user.getUserType()) || UserTypeEnum._08.getKey().equals(user.getUserType()))
                        .collect(Collectors.toList());

            }
        }

        // 按部门ID，查询安装人员
        if (StrUtil.isNotEmpty(bo.getDepartmentId())) {
            return getInstallUserSelect(bo.getDepartmentId());
        }

        // 按公司ID，查询安装人员
        return getInstallUserSelect(bo.getOperateUserCompanyId());
    }

    @Override
    public List<RepairUser> getRepairUsers(QueryRepairUsersBO bo) throws Exception {

        // 按部门ID，查询安装人员
        if (StrUtil.isNotEmpty(bo.getDepartmentId())) {
            return getRepairUserSelect(bo.getDepartmentId());
        }

        // 按公司ID，查询安装人员
        return getRepairUserSelect(bo.getOperateUserCompanyId());
    }
       @Override
   public  List<TUser> getPcRepairUsers(QueryRepairUsersBO bo) throws Exception{

        // 按部门ID，查询安装人员
        if (StrUtil.isNotEmpty(bo.getDepartmentId())) {
            return getInstallUserSelect(bo.getDepartmentId());
        }

        // 按公司ID，查询安装人员
        return getInstallUserSelect(bo.getCompanyId());
    }
    @Override
    public List<String> getUserAreaCodes(Long erUserId) throws Exception {
        List<TUser> users = getUsers(erUserId);
        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }

        // 根据用户列表获取用户的行政区划
        List<String> areaCodes = users.stream()
                .filter(user -> ObjectUtil.isNotNull(user.getAreacode()))
                .map(TUser::getAreacode)
                .collect(Collectors.toList());

        if (CollUtil.isNotEmpty(areaCodes)) {
            return areaCodes;
        }

        return Collections.emptyList();
    }

    @Override
    public List<Map<String, String>> getOtherInstallUserSelectByDept(GetOtherInstallUserVO vo) throws Exception {
        // 校验当前登录人的权限
        validate(vo);
        List<TUser> users = new ArrayList<>();
        // 通过当前登录人及项目ID，查询当前登录人是否加入了施工队
        boolean flag = projectServiceUserAuthService.validateBelongToTeam(vo.getOperateUserId(), vo.getProjectUuid());
        if (flag) {
            // 查询有行政区划代码权限的施工队成员id
            Set<Long> teamUserIdSet = projectServiceUserAuthService.getTeamUserIdList(vo.getOperateUserId(), vo.getProjectUuid(), vo.getAreaCode());
            // 查询施工队成员的用户信息
            users = this.getUsers(new ArrayList<>(teamUserIdSet));
        } else {
            // 查询本部门所有人员信息
            users = getInstallUserSelect(vo.getUserInfo().getDepartmentId());
        }

        if (CollectionUtil.isEmpty(users)) {
            return Collections.emptyList();
        }
        // 组装返回值 - 去掉自己
        return users.stream()
                .filter(ObjectUtil::isNotNull)
                .filter(n -> !vo.getOperateUserId().equals(n.getId()))
                .map(n -> {
                    Map<String, String> map = new HashMap<>();
                    map.put("nickName", n.getNickName());
                    map.put("id", String.valueOf(n.getId()));
                    return map;
                })
                .collect(Collectors.toList());
    }

    @Override
    public Boolean checkHaveForeman(String departmentId) {
        return this.baseMapper.checkHaveForeman(departmentId);
    }


    @Override
    public List<Long> getUserIdList(List<String> departmentIdList, String serviceUserName, String serviceUserPhone) {
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("sfsc", 0);
        if (CollectionUtil.isNotEmpty(departmentIdList)) {
            wrapper.in("departmentId", departmentIdList);
        }
        if (StrUtil.isNotBlank(serviceUserName)) {
            wrapper.like("nickName", serviceUserName);
        }
        if (StrUtil.isNotBlank(serviceUserPhone)) {
            wrapper.eq("phone", serviceUserPhone);
        }
        wrapper.select("id");

        List<TUser> tUsers = this.list(wrapper);
        if (CollectionUtil.isEmpty(tUsers)) {
            return Collections.emptyList();
        }
        return tUsers.stream().map(TUser::getId).distinct().collect(Collectors.toList());
    }

    @Override
    public List<MyTeamInfoDTO> getMyTeamInfoList(Long easyRepairUserId) {
        return this.baseMapper.getMyTeamInfoList(easyRepairUserId);
    }

    @Override
    public Boolean checkIsForeman(String easyRepairUserId) {
        return this.baseMapper.checkIsForeman(easyRepairUserId);
    }

    @Override
    public List<String> getCallCenterUserIdListByEasyRepairUserId(Long easyRepairUserId) {
        return this.baseMapper.getCallCenterUserIdListByEasyRepairUserId(easyRepairUserId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TUser saveERUser(SaveERUserBO bo) throws Exception {
        // 查询当前部门下是否存在易修用户
        TUser user = getUserByERUserIdInDepartment(bo);

        // 查询当前部门下是否存在相同手机号的用户
        if (ObjectUtil.isNull(user)) {
            user = getUserByPhoneInDepartment(bo);
            if (ObjectUtil.isNotNull(user)) {
                // 处理用户账号的行政区划代码
                Set<String> areaCodeSet = new HashSet<>();
                areaCodeSet.add(bo.getAreaCode());
                if (StrUtil.isNotBlank(user.getAreacode())) {
                    areaCodeSet.addAll(Arrays.asList(user.getAreacode().split(";")));
                }
                user.setAreacode(String.join(";", areaCodeSet));
                user.setAreaname(xzqhService.getAreaName(";", areaCodeSet));

                user.setEasyRepairUserId(bo.getErUserId());
                this.updateById(user);
            }
        }

        //用户不存在，需要创建新用户
        if (ObjectUtil.isNull(user)) {

            // 检验当前公司下是否存在相同用户
            validateDuplicateUser(bo.getCompanyId(), bo.getErUserId());

            // 保存用户之前，查询角色
            TRole role = getRoleBeforeSaveUser(bo);

            TUser newUser = new TUser();
            newUser.setUuid(UUID.randomUUID().toString());
            newUser.setUsername(bo.getUsername());
            newUser.setPassword(EncryptedUtil.generate(bo.getPhone(), bo.getUsername()));
            newUser.setNickName(bo.getNickname());
            newUser.setPhone(bo.getPhone());
            newUser.setSex(bo.getSex());
            newUser.setCompanyId(bo.getCompanyId());
            newUser.setDepartmentId(bo.getDepartmentId());
            newUser.setCreateTime(bo.getOperateDate());
            newUser.setEasyRepairUserId(bo.getErUserId());
            newUser.setUserType(UserTypeEnum._02.getKey());
            newUser.setRoleId(role.getRoleId());
            newUser.setSfsc(DeleteEnum._0.getKey());
            newUser.setCreateUid(bo.getOperateUserId());
            newUser.setAreacode(bo.getAreaCode());
            newUser.setAreaname(xzqhService.getAreaName(";", Collections.singleton(bo.getAreaCode())));
            this.save(newUser);

            afterSaveUser(newUser.getUuid(), newUser.getCompanyId(), newUser.getPhone());
            return newUser;
        }

        return user;
    }

    private void validateDuplicateUser(String companyId, Long easyRepairUserId) throws Exception {
        List<TUser> users = this.getUsers(companyId, easyRepairUserId);
        if (CollUtil.isNotEmpty(users)) {
            throw new BusinessException("用户已存在，不可重复添加！");
        }
    }

    @Override
    public TUser getUser(String companyId, Long easyRepairUserId) throws Exception {
        TUser queryUser = new TUser();
        queryUser.setCompanyId(companyId);
        queryUser.setEasyRepairUserId(easyRepairUserId);
        queryUser.setSfsc(DeleteEnum._0.getKey());
        TUser user = this.baseMapper.selectOne(new LambdaQueryWrapper<>(queryUser));
        if (ObjectUtil.isNull(user)) {
            throw new IllegalBusinessException("用户不存在！");
        }
        return user;
    }

    @Override
    public TUser getServiceUserInfo(String projectUuidId, Long easyRepairUserId) {
        return this.baseMapper.getServiceUserInfo(projectUuidId, easyRepairUserId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateUserInfoFromEasyRepair(UpdateUserInfoFromEasyRepairVO vo) throws Exception {
        // 获取易修对应的全部热链云用户
        List<TUser> users = this.getUsers(vo.getEasyRepairUserId());
        if (CollectionUtil.isEmpty(users)) {
            log.error("未查询到关联的热链云用户信息");
            return false;
        }

        for (TUser user : users) {
            user.setNickName(vo.getNickName());
            user.setModifyTime(vo.getOperateDate());
            this.updateById(user);
        }

        return true;
    }

    @Override
    public Set<Long> getUserIdSet(String companyId, String createUserName) {
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("companyId", companyId);
        queryWrapper.like("nickName", createUserName);

        return this.baseMapper.selectList(queryWrapper).stream().map(TUser::getId).collect(Collectors.toSet());
    }

    @Override
    public List<String> getUserPhoneById(String maintainId) throws Exception {
        TUser userInfoByUserId = this.getUserInfoByUserId(maintainId);
        if (ObjectUtil.isNull(userInfoByUserId) || ObjectUtil.isNull(userInfoByUserId.getPhone())) {
            throw new Exception("未获取到当前用户手机号");
        }

        return Collections.singletonList(userInfoByUserId.getPhone());
    }

    private void afterSaveUser(String userUuid, String companyId, String password) throws Exception {
        Company company = businessCompanyService.getCompany(companyId);
        PushUserInfoVO pushUserInfoVO = new PushUserInfoVO();
        pushUserInfoVO.setUuid(userUuid);
        pushUserInfoVO.setCompanyId(companyId);
        pushUserInfoVO.setPassword(password);
        pushUserInfoVO.setCallCenterCompanyId(company.getCcCompanyId());
        this.pushUserInfo(pushUserInfoVO);
    }

    private TRole getRoleBeforeSaveUser(SaveERUserBO bo) throws Exception {
        // 判断是否存在易修扫码角色
        TRole role = systemRoleService.getERUserRole(bo.getCompanyId());

        // 新增角色
        if (ObjectUtil.isNull(role)) {
            role = new TRole();
            role.setRoleId(UUID.randomUUID().toString());
            role.setUuid(UUID.randomUUID().toString());
            role.setName("易修人员角色");
            role.setDesc("易修用户在热链云对应的角色");
            role.setCompanyId(bo.getCompanyId());
            role.setIsAuthorRole("0");
            role.setEnabled(true);
            role.setSfsc(DeleteEnum._0.getKey());
            role.setCreateTime(bo.getOperateDate());
            role.setCreateUid(bo.getOperateUserId());
            systemRoleService.save(role);
        }

        return role;
    }

    private TUser getUserByERUserIdInDepartment(SaveERUserBO bo) throws Exception {
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("companyId", bo.getCompanyId());
//        wrapper.eq("departmentId", bo.getDepartmentId());
        wrapper.eq("easy_repair_user_id", bo.getErUserId());
        wrapper.eq("sfsc", DeleteEnum._0.getKey());
        return this.getOne(wrapper);
    }

    private TUser getUserByPhoneInDepartment(SaveERUserBO bo) throws Exception {
        QueryWrapper<TUser> wrapper = new QueryWrapper<>();
        wrapper.eq("companyId", bo.getCompanyId());
//        wrapper.eq("departmentId", bo.getDepartmentId());
        wrapper.eq("phone", bo.getPhone());
        wrapper.eq("sfsc", DeleteEnum._0.getKey());
        return this.getOne(wrapper);
    }

    @Override
    public List<TUser> getUsers(String companyOrDepartmentId, UserTypeEnum userTypeEnum) throws Exception {
        if (StrUtil.isEmpty(companyOrDepartmentId)) {
            throw new MissBusinessParameterException("传入公司或部门ID");
        }
        List<TUser> users = getUsers(companyOrDepartmentId);

        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }

        if (ObjectUtil.isNotNull(userTypeEnum)) {
            return users.stream()
                    .filter(user -> userTypeEnum.getKey().equals(user.getUserType()))
                    .collect(Collectors.toList());
        }

        return users;
    }
    public List<RepairUser> getRepairUser(String companyOrDepartmentId, UserTypeEnum userTypeEnum) throws Exception {
        if (StrUtil.isEmpty(companyOrDepartmentId)) {
            throw new MissBusinessParameterException("传入公司或部门ID");
        }
        List<RepairUser> users = getRepairUser(companyOrDepartmentId);

        if (CollUtil.isEmpty(users)) {
            return Collections.emptyList();
        }

        if (ObjectUtil.isNotNull(userTypeEnum)) {
            return users.stream()
                    .filter(RepairUser -> userTypeEnum.getKey().equals(RepairUser.getUserType()))
                    .collect(Collectors.toList());
        }

        return users;
    }

    @Override
    public Object getInstallPersonList(NullVO vo) throws Exception {
        GetInstallPersonListBO getInstallPersonListBo = new GetInstallPersonListBO();
        BeanUtils.copyProperties(vo, getInstallPersonListBo);

        return callCenterService.getInstallPersonList(getInstallPersonListBo);
    }

    private TUser getSystemUser(String companyId, Long userId) throws Exception {
        Company company = businessCompanyService.getCompany(companyId);
        TUser queryUser = new TUser();
        queryUser.setId(userId);
        queryUser.setCompanyId(company.getCompanyid());
        TUser user = this.baseMapper.selectOne(new QueryWrapper<>(queryUser));
        if (ObjectUtil.isNull(user)) {
            throw new IllegalBusinessException("用户不存在");
        }
        return user;
    }

    private TUserBo getSystemUser(String companyId, String uuid) throws Exception {
        Company company = businessCompanyService.getCompany(companyId);
        TUser queryUser = new TUser();
        queryUser.setUuid(uuid);
        queryUser.setCompanyId(company.getCompanyid());
        TUser user = this.baseMapper.selectOne(new QueryWrapper<>(queryUser));
        if (ObjectUtil.isNull(user)) {
            throw new IllegalBusinessException("用户不存在");
        }
        TUserBo tUserVo = new TUserBo();
        BeanUtils.copyProperties(user, tUserVo);
        tUserVo.setCompanyType(company.getCompanytype());
        tUserVo.setCallCenterCompanyId(company.getCcCompanyId());
        tUserVo.setNes_companyId(company.getNesCompanyid());
        return tUserVo;
    }

    private TUserBo getSystemUserByErUserId(String companyId, Long erUserId) throws Exception {
        Company company = businessCompanyService.getCompany(companyId);
        TUser queryUser = new TUser();
        queryUser.setEasyRepairUserId(erUserId);
        queryUser.setCompanyId(company.getCompanyid());
        queryUser.setSfsc(DeleteEnum._0.getKey());
        TUser user = this.baseMapper.selectOne(new QueryWrapper<>(queryUser));
        if (ObjectUtil.isNull(user)) {
            throw new IllegalBusinessException("用户不存在");
        }
        TUserBo tUserVo = new TUserBo();
        BeanUtils.copyProperties(user, tUserVo);
        tUserVo.setCallCenterCompanyId(company.getCcCompanyId());
        tUserVo.setNes_companyId(company.getNesCompanyid());
        return tUserVo;
    }

    // 校验查询转单师傅列表参数
    private void validate(GetOtherInstallUserVO vo) throws Exception {
        // 校验入参是否合法
        if (ObjectUtil.isNull(vo.getWorkOrderId())) {
            throw new MissBusinessParameterException("工单ID");
        }
        // 通过工单id查询项目uuid
        WorkOrderInfo workOrderInfo = workOrderService.getWorkOrderInfo(vo.getWorkOrderId());
        if (ObjectUtil.isNull(workOrderInfo)) {
            throw new BusinessException("安装工单不存在");
        }
        // 查询工单关联的项目id
        Long projectId = crmFlowTableRelationshipService.getProjectId(workOrderInfo.getId());
        // 如果入参是项目uuid - 校验入参的项目uuid是否合法
        TProject projectDetail = tProjectService.getProjectDetail(projectId);
        if (ObjectUtil.isNull(projectDetail)) {
            throw new BusinessException("工单关联的项目不存在!");
        }
        vo.setProjectUuid(projectDetail.getUuid());
        vo.setAreaCode(workOrderInfo.getXzqhdm());
    }

}
